package com.young4j.springdemo.controller;

import com.young4j.springdemo.config.elasticsearch.ElastisearchProperties;
import com.young4j.springdemo.domain.*;
import io.searchbox.client.JestClient;
import io.searchbox.core.*;
import io.searchbox.indices.Analyze;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

/**
 * @Description
 * @Author yf
 * @Date 2019/1/2 16:26
 **/
@RestController
@RequestMapping("/es")
public class ElasticsearchController {
    Logger log = LoggerFactory.getLogger(ElasticsearchController.class);
   /* @Autowired
    private StudentRepository studentRepository;*/
    @Autowired
    private JestClient jestClient;
    @Autowired
    private ElastisearchProperties elastisearchProperties;

    /*@RequestMapping("/add")
    public Object add(){
        Random random = new Random();
        long id = random.nextLong();

        Estudent estudent = new Estudent(id, String.valueOf(id));
        studentRepository.save(estudent);
        return estudent.toString();
    }
    @RequestMapping("/list")
    public Object list(){
        Iterable<Estudent> all = studentRepository.findAll();
        return all;
    }*/
    @RequestMapping("/jestAnalyze")
    public Object jestAnalyze(String keyword) {
        return null;
    }
    @RequestMapping("/jestAdd")
    public Object jestAdd(String keyword,String author){
        Random random = new Random();
        long id = random.nextLong();

        ESListenBook entity = new ESListenBook();
        entity.setKeyword(keyword);
        entity.setAuthor(author);
        //entity.setId((int)id);
        entity.setType(1);
        entity.setStatus(1);
        entity.setPlayer(entity.getAuthor());
        entity.setUpdateTime(new Date().getTime());
        try {

            Analyze ik = new Analyze.Builder()
                    .index(elastisearchProperties.getIndex()).analyzer("ik_smart").build();
            Index build = new Index.Builder(entity).index(elastisearchProperties.getIndex()).type(elastisearchProperties.getType()).refresh(true).build();

            DocumentResult execute = jestClient.execute(build);
            log.info("execute = {}",execute);

        } catch (IOException e) {
            log.error("保存失败",e);
        }
        return entity;
    }
    @RequestMapping("/jestSearch")
    public Object jestSearch(SearchListenBookDTO bookDTO) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (bookDTO.getId() != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery(ListenBookDB.Field.ID, bookDTO.getId()));
        }
        if (StringUtils.isNotBlank(bookDTO.getName())) {
            boolQueryBuilder
                    .must(QueryBuilders.matchQuery(ListenBookDB.Field.NAME, bookDTO.getName()));
        }
        if (StringUtils.isNotBlank(bookDTO.getAuthor())) {
            boolQueryBuilder
                    .must(QueryBuilders.matchQuery(ListenBookDB.Field.AUTHOR, bookDTO.getAuthor()));
        }
        if (StringUtils.isNotBlank(bookDTO.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery(ListenBookDB.Field.KEYWORD, bookDTO.getKeyword()));
        }
        if (bookDTO.getStatus() != null) {
            boolQueryBuilder
                    .must(QueryBuilders.termQuery(ListenBookDB.Field.STATUS, bookDTO.getStatus()));
        }
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort(ListenBookDB.Field.UPDATE_TIME, SortOrder.DESC);

        HighlightBuilder keywordBuilder = new HighlightBuilder();
        keywordBuilder.preTags("<span stype=\"color:red\">");
        keywordBuilder.postTags("</span>");
        keywordBuilder.field("keyword");
        keywordBuilder.field("author");

        /*HighlightBuilder.Field highlightKeyword = new HighlightBuilder.Field("keyword");
        highlightKeyword.highlighterType("unified");
        keywordBuilder.field(highlightKeyword);

        HighlightBuilder.Field hgthlightAuthor = new HighlightBuilder.Field("author");
        keywordBuilder.field(hgthlightAuthor);*/

        searchSourceBuilder.highlighter(keywordBuilder);
        searchSourceBuilder.from((bookDTO.getPage() - 1) * bookDTO.getSize())
                .size(bookDTO.getSize());
        Search search =
                new Search.Builder(searchSourceBuilder.toString()).addIndex(elastisearchProperties.getIndex())
                        .addType(elastisearchProperties.getType()).build();
        SearchResult result = null;
        List<ESListenBook> list = new ArrayList<>();
        try {
            result = jestClient.execute(search);
            List<ESListenBook> notHighlight = result.getSourceAsObjectList(ESListenBook.class, false);
           /* if(notHighlight != null)
                notHighlight.forEach(n -> System.out.println(n.toString()));*/
            log.info("HOTHIGHLIGHT:" + notHighlight.toString());
            List<SearchResult.Hit<ESListenBook, Void>> hits = result.getHits(ESListenBook.class);
            for (SearchResult.Hit<ESListenBook, Void> hit : hits) {
                ESListenBook source = hit.source;
                Map<String, List<String>> highlight = hit.highlight;
                if (highlight != null) {
                    List<String> keyword = highlight.get("keyword");
                    if (keyword != null) {
                        source.setKeyword(keyword.get(0));
                        //不在这里list.add 是因为如果没有搜索条件，结果就会没数据
                    }
                    List<String> author = highlight.get("author");
                    if (author != null) {
                        source.setAuthor(author.get(0));
                    }
                }
                list.add(source);
            }
            if (result == null) {
                return null;
            }
        } catch (Exception e) {
            log.error("查询失败", e);
        }
        Long total = result.getTotal();
        //List<ESListenBook> list = result.getSourceAsObjectList(ESListenBook.class, true);
        PageBean<ESListenBook> pageBean = new PageBean(list, total, bookDTO.getPage(), bookDTO.getSize());
        return pageBean;
    }

    @RequestMapping("/jestDelete")
    public Object jestDelete(String id) {
        try {
            jestClient.execute(new Delete.Builder(id).index(elastisearchProperties.getIndex()).type(elastisearchProperties.getType()).build());
        } catch (IOException e) {
            log.error("删除失败！",e);
            e.printStackTrace();
        }
        return "success";
    }
}
